package cn.com.elite;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.encoding.XMLType;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import sun.misc.BASE64Decoder;

public class RSThread implements Runnable{
	private static final Log log=LogFactory.getLog(RSThread.class);
	public static cn.com.elite.EliteBean ebeana;
	public static String address;
	private boolean flag = true; 
	private static int HZ=1000*60*60;
	private static String time_flag="";
	private static String RunningTime="";
	private static String daytime="";
	private static String branchNO="";
	public cn.com.elite.EliteBean getEbeana() {
		return ebeana;
	}
	public void setEbeana(cn.com.elite.EliteBean ebeana) {
		this.ebeana=ebeana;
	}
	public static String getAddress() {
		return address;
	}
	public static void setAddress(String address) {
		RSThread.address = address;
	}
	
	private static String getFromBASE64(String s){
		if(s==null){
			return null;
		}
		BASE64Decoder decoder=new BASE64Decoder();
		try{
			byte[] b=decoder.decodeBuffer(s); 
			return new String(b); 
		}catch(Exception e){
			log.error("getFromBASE64过程出错:"+EliteUtil.getERRO(e));  
			return null;
		}
	}
	public static void main(String[] args) throws DocumentException{
		String inputXml="<com.card.interfaceData.createCard.Message><requestMessage><cardParams><id>0</id><cardOrderId>1008121000001101</cardOrderId><systemType>1008</systemType><branchNO>12</branchNO><type>10</type><cardProductId>1312</cardProductId><cardProductBranch>11</cardProductBranch><ecno>0202573564016</ecno><buyQuantity>100</buyQuantity><batchNO>10</batchNO><isCardCodeSaved>0</isCardCodeSaved></cardParams></requestMessage><responseMessage><resultFlag>0</resultFlag><errorInfoList><com.card.interfaceData.createCard.ErrorInfo><no>1</no><code>21</code><message>参数不正确:</message><errorFrom>branchNO+cardProductBranch</errorFrom><errorValue>12 + 11</errorValue></com.card.interfaceData.createCard.ErrorInfo></errorInfoList></responseMessage></com.card.interfaceData.createCard.Message>";
		String inputXml1=" <com.card.interfaceData.createCard.Message><requestMessage><cardParams><id>0</id><cardOrderId>1008121000001111</cardOrderId><systemType>1008</systemType><branchNO>12</branchNO><type>10</type><cardProductId>1313</cardProductId><cardProductBranch>12</cardProductBranch><ecno>6955168731585</ecno><buyQuantity>100</buyQuantity><batchNO>10</batchNO><isCardCodeSaved>1</isCardCodeSaved></cardParams></requestMessage><responseMessage><resultFlag>1</resultFlag><errorInfoList/><cardCodeInfoList><com.card.interfaceData.createCard.CardCodeInfo><id>0</id><cardOrderId>1008121000001111</cardOrderId><cardCode>1313121055837516</cardCode><cardPassword>ODU5NjY0MzA=</cardPassword><cardMD5Password>0048359C600E2C3080333077ACD91258</cardMD5Password></com.card.interfaceData.createCard.CardCodeInfo><com.card.interfaceData.createCard.CardCodeInfo><id>0</id><cardOrderId>1008121000001111</cardOrderId><cardCode>1313121055837517</cardCode><cardPassword>OTE3Nzc3NzY=</cardPassword><cardMD5Password>B983FE7747FD903BFE1B19A76D5A869D</cardMD5Password></com.card.interfaceData.createCard.CardCodeInfo></cardCodeInfoList></responseMessage></com.card.interfaceData.createCard.Message>"; 
		Document document=DocumentHelper.parseText(inputXml1);
		Element memberElm=(Element) document.getRootElement(); 
		Element memberElm0=memberElm.element("responseMessage");
		Element memberElm1=memberElm0.element("resultFlag");
		String responseMessage=memberElm1.getText();
		if(responseMessage.equals("0")){
			Element memberElm2=memberElm0.element("errorInfoList");
			Element memberElm3=memberElm2.element("com.card.interfaceData.createCard.ErrorInfo");
			String a=memberElm3.elementText("code");
			String b=memberElm3.elementText("message");
			String c=memberElm3.elementText("errorFrom");
			String d=memberElm3.elementText("errorValue");
			String sql="insert into largess_prog_log(guid,log_date,log_desc,log_xml1,S_CODE,S_MESSAGE,S_errorFrom,S_errorValue)values(sys_guid(),sysdate,'调用激活卡接口完毕','"+inputXml+"','"+a+"','"+b+"','"+c+"','"+d+"')";
		    System.out.println(sql);
		}else if(responseMessage.equals("1")){
			Element memberElm01=memberElm.element("requestMessage");
			Element memberElm02=memberElm01.element("cardParams");
			String cardProductId=memberElm02.elementText("cardProductId");
			Element memberElm2=memberElm0.element("cardCodeInfoList");
			for(Iterator it=memberElm2.elementIterator();it.hasNext();){
				Element element3=(Element)it.next();
				String cardCode=element3.elementText("cardCode");
				String cardPassword=element3.elementText("cardPassword");
				cardPassword=getFromBASE64(cardPassword);
				String sql="insert into ActivateCard_Pool (Card_Pool_Guid,CARD,PASSWORD,CardProductId,STATE)Values(sys_guid(),'"+cardCode+"','"+cardPassword+"','"+cardProductId+"',0)";
			    System.out.println(sql);
			}
		}else{
			log.error("responseMessage:"+responseMessage);
		}
	}
	private void parseXml(String xml)throws Exception{
		Document document=DocumentHelper.parseText(xml);
		Element memberElm=(Element) document.getRootElement(); 
		Element memberElm0=memberElm.element("responseMessage");
		Element memberElm1=memberElm0.element("resultFlag");
		String responseMessage=memberElm1.getText();
		if(responseMessage.equals("0")){
			Element memberElm2=memberElm0.element("errorInfoList");
			Element memberElm3=memberElm2.element("com.card.interfaceData.createCard.ErrorInfo");
			String a=memberElm3.elementText("code");
			String b=memberElm3.elementText("message");
			String c=memberElm3.elementText("errorFrom");
			String d=memberElm3.elementText("errorValue");
			String sql="insert into largess_prog_log(guid,log_date,log_desc,log_xml1,S_CODE,S_MESSAGE,S_errorFrom,S_errorValue)values(sys_guid(),sysdate,'调用激活卡接口完毕','"+xml+"','"+a+"','"+b+"','"+c+"','"+d+"')";
			log.info(sql+":"+ebeana.update(sql));
		}else if(responseMessage.equals("1")){
			try{
				log.info("成功resultlist:"+ebeana.update("insert into largess_prog_log(guid,log_date,log_desc,log_xml1)values(sys_guid(),sysdate,'调用激活卡接口完毕','"+xml+"')"));
			}catch(Exception e){
				log.error("成功resultlist执行过程错误:"+EliteUtil.getERRO(e));  
				log.info("成功resultlist补:"+ebeana.update("insert into largess_prog_log(guid,log_date,log_desc,log_xml1)values(sys_guid(),sysdate,'调用激活卡接口完毕','字段过长')"));
			}
			Element memberElm01=memberElm.element("requestMessage");
			Element memberElm02=memberElm01.element("cardParams");
			String cardProductId=memberElm02.elementText("cardProductId");
			Element memberElm2=memberElm0.element("cardCodeInfoList");
			for(Iterator it=memberElm2.elementIterator();it.hasNext();){
				Element element3=(Element)it.next();
				String cardCode=element3.elementText("cardCode");
				String cardPassword=element3.elementText("cardPassword");
				cardPassword=getFromBASE64(cardPassword);
				String sql="insert into ActivateCard_Pool (Card_Pool_Guid,CARD,PASSWORD,CardProductId,STATE)Values(sys_guid(),'"+cardCode+"','"+cardPassword+"','"+cardProductId+"',0)";
				log.info(sql+":"+ebeana.update(sql));
			}
		}else{
			log.error("responseMessage:"+responseMessage);
		}
	}
	private String getReturnXml(String xml)throws Exception{
		Service service=new Service();
		Call call=(Call)service.createCall();
		call.setTargetEndpointAddress(new java.net.URL(address)); 
		call.setOperationName(new QName("http://createCard.interfaceData.card.com","generateCard"));   //要访问的方法
		call.addParameter("inputXML",XMLType.XSD_STRING,ParameterMode.IN);
		call.setReturnType(XMLType.XSD_STRING); //设置返回值类型
        String i=(String)call.invoke(new Object[]{xml});
        return i;
	}
	private String getRandom() throws Exception{
		String a="";
		Random rnd=new Random();
        for(int i=0;i<13;i++){
        	a=a+rnd.nextInt(9);
        }
        return a;
	}
	private void dorun(){
		try{
			List list=ebeana.chaxun(" select MAX_Threshold,EachExtraction from ActivateCard_Threshold ");
			Map map=(Map)list.get(0);
			String MAX_Threshold=String.valueOf(map.get("MAX_Threshold"));
			log.info("MAX_Threshold:"+MAX_Threshold);
			String buyQuantity=String.valueOf(map.get("EachExtraction"));
			log.info("buyQuantity:"+buyQuantity);
			List lis1=ebeana.chaxun(" SELECT  P.POL_CODE,CARDPRODUCTBRANCH FROM POLICY P WHERE P.POL_TYPE=4 ");
			if(lis1!=null&&lis1.size()>0){
				for(int i=0;i<lis1.size();i++){
					Map map1=(Map)lis1.get(i);
					String cardProductId=String.valueOf(map1.get("POL_CODE"));
					log.info("cardProductId:"+cardProductId);
					String cardProductBranch=String.valueOf(map1.get("CARDPRODUCTBRANCH"));
					log.info("cardProductBranch:"+cardProductBranch);
					int num=ebeana.count("select count(*) from ActivateCard_Pool where CardProductId='"+cardProductId+"'");
					if(num<Integer.parseInt(MAX_Threshold)){
						int diff=0;
		                int diff_temp1=(Integer.parseInt(MAX_Threshold)-num)%Integer.parseInt(buyQuantity);
		                if(diff_temp1>0){
		                	diff=(Integer.parseInt(MAX_Threshold)-num)/Integer.parseInt(buyQuantity)+1;
		                }else{
		                	int diff_temp=Integer.parseInt(MAX_Threshold)-num;
		                	if(diff_temp>0){
		                		diff=(Integer.parseInt(MAX_Threshold)-num)/Integer.parseInt(buyQuantity);
		                	}else{
		                		diff=0;
		                	}
		                }
		                log.info("diff:"+diff);
		                for(int n=0;n<diff;n++){
		                	try{
		                		String cardOrderId=ebeana.chaxunString("SELECT 1008||ORGID||10||LPAD(MY_TABLE_SEQ.nextval ,8,'0') FROM C_PROVINCE");
		                		String ecno=getRandom();
		                		String InputXml="<message><requestMessage><cardParams><id>0</id><cardOrderId>"+cardOrderId+"</cardOrderId><systemType>1008</systemType><branchNO>"+branchNO+"</branchNO><type>10</type><cardProductId>"+cardProductId+"</cardProductId><cardProductBranch>"+cardProductBranch+"</cardProductBranch><ecno>"+ecno+"</ecno><buyQuantity>"+buyQuantity+"</buyQuantity><batchNO>10</batchNO></cardParams></requestMessage><responseMessage/></message>";
		                        log.info("InputXml:"+InputXml);
		                        int result=ebeana.update("insert into largess_prog_log(guid,log_date,log_desc,log_xml)values(sys_guid(),sysdate,'开始调用激活卡接口','"+InputXml+"')");
		                        log.info("result:"+result);
		                        String returnXml=getReturnXml(InputXml);
		                        log.info("returnXml:"+returnXml);
		                        parseXml(returnXml);
		                	}catch(Exception e){
		                		log.error("SQL查询过程出错:"+EliteUtil.getERRO(e));  
		                	}
		                }
					}
				}
			}
		}catch(Exception e){
			log.error("dorun()执行过程错误:"+EliteUtil.getERRO(e));  
		}
	}
	public void run(){
		try{
			branchNO=ebeana.chaxunString("SELECT ORGID FROM C_PROVINCE");
			log.info("branchNO:"+branchNO);
			List list=ebeana.chaxun(" SELECT RunningFrequency,RunningTime FROM ActivateCard_Threshold ");
			Map map=(Map)list.get(0);
			String RunningFrequency=String.valueOf(map.get("RunningFrequency"));
			log.info("RunningFrequency:"+RunningFrequency);
			RunningTime=String.valueOf(map.get("RunningTime"));
			log.info("RunningTime:"+RunningTime);
			if(RunningFrequency.equals("1")){                   //按小时
				time_flag="H";
			}else if(RunningFrequency.equals("2")){              //按天
				time_flag="D";
			}else{
				log.error("RunningFrequency="+RunningFrequency+"不合法");
				return;
			}
			
		}catch(Exception e){
			log.error("RSThread初始化错误:"+EliteUtil.getERRO(e));  
			return;
		}
		while(flag){
			try{
				if(time_flag.equals("H")){
					dorun();
				}else if(time_flag.equals("D")){
					Date date=new Date();
					String ee=String.format("%tR",date); //获取现在几点
					String dd=String.format("%tF",date); //获取现在几号
					String now1=ee.substring(0,2);
					log.info("dd:"+dd);
					log.info("daytime:"+daytime);
					log.info("now1:"+now1);
					if(now1.equals(RunningTime)&&!dd.equals(daytime)){
						dorun();
						daytime=dd;
					}				
				}else{
					log.error("time_flag="+time_flag+"不合法");
					return;
				}
			}catch(Exception e){
				log.error("RSThread执行过程错误:"+EliteUtil.getERRO(e));  
			}
			
			try{
				Thread.sleep(HZ);
			}catch(Exception e){
				log.error("RSThread休眠错误:"+EliteUtil.getERRO(e));  
			}
		}	
	}

}
